package com.mp.approvalreq.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.dao.TemplateFolderDao;
import com.mp.approvalreq.entity.TemplateFolder;
import com.plusmoney.util.SQLLogger;
import com.plusmoney.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TemplateFolderDaoImpl extends AbstractDao implements TemplateFolderDao {

    private static final Logger logger = LoggerFactory.getLogger(TemplateFolderDaoImpl.class);


    private Connection connection;

    public TemplateFolderDaoImpl(Connection connection) {
        this.connection = connection;
    }

    public PreparedStatement getPreparedStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    String getQuerySql(String condition) {
        final String query = "select id, company_id, name, color, sort,"
                + " templates"
                + " from sys_approval_template_folder";
        return String.format("%s %s", query, condition);
    }

    @Override
    TemplateFolder getObject(ResultSet rs) throws SQLException {
        TemplateFolder folder = new TemplateFolder();
        folder.setId(rs.getInt(1));
        folder.setCompanyId(rs.getInt(2));
        folder.setName(rs.getString(3));
        folder.setColor(rs.getString(4));
        folder.setSort(rs.getInt(5));

        folder.setTemplates(rs.getString(6));
        return folder;
    }


    @Override
    public List<TemplateFolder> selectTemplateFolders(Integer companyId) throws SQLException {
        List<TemplateFolder> list = new ArrayList<>();
        String sql = getQuerySql("where company_id = ? and state = 1 order by sort");

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, companyId);
            logger.info(SQLLogger.logSQL(sql, companyId));

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    list.add(getObject(rs));
                }
            }
        }
        return list;
    }

    @Override
    public void insertTemplateFolder(TemplateFolder templateFolder) throws SQLException {
        String sql = "insert into sys_approval_template_folder set company_id = ?, name = ?, color = ?, sort = ?, templates = ?, create_time = now()";

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, templateFolder.getCompanyId());
            ps.setString(2, templateFolder.getName());
            ps.setString(3, templateFolder.getColor());
            ps.setInt(4, templateFolder.getSort());
            String templates = Utils.isEmpty(templateFolder.getTemplates()) ? null : JSONObject.toJSONString(templateFolder.getTemplates());
            ps.setString(5, templates);
            logger.info(SQLLogger.logSQL(sql, templateFolder.getCompanyId(), templateFolder.getName(), templateFolder.getColor(), templateFolder.getSort(), templates));

            ps.executeUpdate();
        }
    }

    @Override
    public void updateBatchTemplateFolder(List<TemplateFolder> templateFolders) throws SQLException {
        String sql = "update sys_approval_template_folder set"
                + " company_id = ?, name = ?, color = ?, sort = ?, templates = ?, update_time = now()"
                + " where id = ? and company_id = ?  limit 1";

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            for (TemplateFolder templateFolder : templateFolders) {
                ps.setInt(1, templateFolder.getCompanyId());
                ps.setString(2, templateFolder.getName());
                ps.setString(3, templateFolder.getColor());
                ps.setInt(4, templateFolder.getSort());
                String templates = Utils.isEmpty(templateFolder.getTemplates()) ? null : JSONObject.toJSONString(templateFolder.getTemplates());
                ps.setString(5, templates);

                ps.setInt(6, templateFolder.getId());
                ps.setInt(7, templateFolder.getCompanyId());
                logger.info(SQLLogger.logSQL(sql, templateFolder.getCompanyId(), templateFolder.getName(), templateFolder.getColor(), templateFolder.getSort(),
                        templates, templateFolder.getId(), templateFolder.getCompanyId()));

                ps.addBatch();
            }
            ps.executeBatch();
        }

    }

    @Override
    public void deleteTemplateFolder(Integer folderId, Integer companyId) throws SQLException {
        String sql = "update sys_approval_template_folder set state = 2, update_time = now() where id = ? and company_id = ? limit 1";

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, folderId);
            ps.setInt(2, companyId);
            logger.info(SQLLogger.logSQL(sql, folderId, companyId));

            ps.executeUpdate();
        }
    }

    @Override
    public TemplateFolder selectTemplateFolderById(Integer id) throws SQLException {
        String sql = getQuerySql("where id = ?");

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, id);
            logger.info(SQLLogger.logSQL(sql, hashCode()));

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return getObject(rs);
                }
            }
        }
        return null;
    }
}
